﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System.Web.UI.HtmlControls;
using DotNetNuke.Security;
using DotNetNuke.Common;
using DNNToolkit.Modules.CityTaxLocator.Components;
using DNNToolkit.Modules.Resource;
using System.Data;
using System.Web;

namespace DNNToolkit.Modules.CityTaxLocator
{
    /// <summary>
    /// The ViewCityTaxLocator class displays the content.
    /// </summary>
    public partial class ViewCityTaxLocator : PortalModuleBase, IActionable
    {

        #region Private Members
        private string headerTemplate;

        /// <summary>
        /// Gets the header template.
        /// </summary>
        /// <value>The header template.</value>
        private string HeaderTemplate
        {
            get
            {
                if (headerTemplate == null)
                {
                    if (!string.IsNullOrEmpty((string)Settings["headertemplate"]))
                        headerTemplate = (string)Settings["headertemplate"];
                    else
                        headerTemplate = Localization.GetString("HeaderTemplate.Text", LocalResourceFile);
                }
                return headerTemplate;
            }
        }

        private string footerTemplate;
        /// <summary>
        /// Gets the footer template.
        /// </summary>
        /// <value>The footer template.</value>
        private string FooterTemplate
        {
            get
            {
                if (string.IsNullOrEmpty(footerTemplate))
                {
                    if (!string.IsNullOrEmpty((string)Settings["footertemplate"]))
                        footerTemplate = (string)Settings["footertemplate"];
                    else
                        footerTemplate = Localization.GetString("FooterTemplate.Text", LocalResourceFile);
                }
                return footerTemplate;
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Register ModalBox.
        /// </summary>
        private void RegisterModalBox()
        {
            List<string> srcList = new List<string>();
            srcList.AddRange(new string[]{
            "~/DesktopModules/DNNToolkit.CityTaxLocator/includes/lib/prototype.js",
            "~/DesktopModules/DNNToolkit.CityTaxLocator/includes/lib/scriptaculous.js?load=effects",
            "~/DesktopModules/DNNToolkit.CityTaxLocator/includes/lib/effects.js",
            "~/DesktopModules/DNNToolkit.CityTaxLocator/includes/modalbox.js"});
            foreach (string src in srcList)
            {
                HtmlGenericControl scriptCtrl = new HtmlGenericControl("script");
                scriptCtrl.Attributes.Add("type", "text/javascript");
                scriptCtrl.Attributes.Add("src", ResolveUrl(src));
                Page.Header.Controls.Add(scriptCtrl);
            }
            HtmlGenericControl linktCtrl = new HtmlGenericControl("link");
            linktCtrl.Attributes.Add("rel", "stylesheet");
            linktCtrl.Attributes.Add("href", ResolveUrl("~/DesktopModules/DNNToolkit.CityTaxLocator/includes/modalbox.css"));
            linktCtrl.Attributes.Add("media", "screen");
            Page.Header.Controls.Add(linktCtrl);
        }

        /// <summary>
        /// Populates the template.
        /// </summary>
        private void PopulateTemplate()
        {
            // set header template
            Label headerTemplateLabel = new Label();
            headerTemplateLabel.Text = HeaderTemplate;
            mHeaderSettingPlaceHolder.Controls.Clear();
            mHeaderSettingPlaceHolder.Controls.Add(headerTemplateLabel);

            // set footer template
            Label footerTemplateLabel = new Label();
            footerTemplateLabel.Text = FooterTemplate;
            mFooterSettingPlaceHolder.Controls.Clear();
            mFooterSettingPlaceHolder.Controls.Add(footerTemplateLabel);
        }

        /// <summary>
        /// Set the press down event.
        /// </summary>
        private void SetPressDownEvent()
        {
            string buttonid = mSearchButton.ClientID;
            mCityTextBox.Attributes.Remove("onkeydown");
            mCodeTextBox.Attributes.Remove("onkeydown");
            mCityTextBox.Attributes.Add("onkeydown", "return GetFocus('" + buttonid + "');");
            mCodeTextBox.Attributes.Add("onkeydown", "return GetFocus('" + buttonid + "');");
        }

        /// <summary>
        /// Search the specified state.
        /// </summary>
        /// <param name="state">The state string.</param>
        /// <param name="city">The city string.</param>
        /// <param name="code">The code string.</param>
        /// <returns></returns>
        private bool Search(string state, string city, string code)
        {
            if (!ValidateSearchParameter(state, city, code))
                return false;

            bool hasFound = false;
            bool hasMultipleRecordes = false;
            string strHTML = "";

            CityTaxLocatorController controller = new CityTaxLocatorController();
            List<CityTaxInfo> list = controller.SearchCityTax(state, city, code);
            hasFound = list.Count > 0;
            hasMultipleRecordes = list.Count > 1;
            if (!hasFound) // can not find the records
            {
                strHTML = Localization.GetString("RecordNotBeFound.Prompt", this.LocalResourceFile);
                ShowMessage(city, code, strHTML);
                
                mDataDataList.Visible = false;
                mPrintTable.Visible = false;
            }
            else
            {
                if (hasMultipleRecordes)
                {
                    strHTML = Localization.GetString("RecordBeFoundMultiple.Prompt", this.LocalResourceFile);
                    ShowMessage(city, code, strHTML);
                }
                //bind data
                BindData(list);                
            }
            return hasFound;
        }

        /// <summary>
        /// Validat the search parameter.
        /// </summary>
        /// <param name="state">The state string.</param>
        /// <param name="city">The city string.</param>
        /// <param name="code">The code string.</param>
        /// <returns></returns>
        private bool ValidateSearchParameter(string state, string city, string code)
        {
            if (!string.IsNullOrEmpty(code.Trim()))
                return true;
            if (!string.IsNullOrEmpty(state) && !string.IsNullOrEmpty(city.Trim()) && city.Trim().Length >= 2)
                return true;
            return false;
        }

        /// <summary>
        /// Show the message.
        /// </summary>
        /// <param name="city">The city string.</param>
        /// <param name="code">The code string.</param>
        /// <param name="strHTML">The STR HTML.</param>
        private void ShowMessage(string city, string code, string strHTML)
        {
            string message = "";
            if (!string.IsNullOrEmpty(code.Trim()))
                message = string.Format(strHTML, "local code", code);
            else
                message = string.Format(strHTML, "city", city);
            mMessageControl.ShowMessage(message);
        }

        /// <summary>
        /// Add items to the State DropDownList.
        /// </summary>
        private void PopulateStates()
        {
            CityTaxLocatorController controller = new CityTaxLocatorController();
            List<string> list = controller.SearchStates();
            mStateDropDown.Items.Clear();
            foreach (string item in list)
            {
                mStateDropDown.Items.Add(item);
            }
            if (list.Count > 0)
                mStateDropDown.SelectedIndex = 0;
        }


        /// <summary>
        /// Sets the index of the combo.
        /// </summary>
        /// <param name="combo">The combo.</param>
        /// <param name="value">The value.</param>
        private void SetComboIndex(System.Web.UI.WebControls.DropDownList combo, string value)
        {
            if (combo.Items.Count > 0)
            {
                for (int i = 0; i < combo.Items.Count; i++)
                {
                    if (combo.Items[i].Value == value)
                    {
                        combo.SelectedIndex = i;
                        return;
                    }
                }
                combo.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// init some CityTaxLocato info.
        /// </summary>
        private void InitInfo()
        {
            CityTaxLocatorController controller = new CityTaxLocatorController();
            if (controller.GetCityTaxRecordCount() > 0)
            {
                CityTaxCommentInfo comment = controller.GetCityTaxComment();
                string updatePrompt = Localization.GetString("Update.Prompt", this.LocalResourceFile);
                mLastUpdatePrompt.InnerHtml = string.Format(updatePrompt, comment.LastUpdate.ToLongDateString());
                if (!mDataDataList.Visible && !mDataDataList.Visible)
                    mAdditionResourceControl.ShowMessage(this);
                else
                    mAdditionResourceControl.Visible = false;
            }
            else
                mLastUpdatePrompt.InnerHtml = string.Empty;
        }

        public DataTable BindData(List<CityTaxInfo> list)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CityTaxID", typeof(double));
            dt.Columns.Add("AdditionalJur", typeof(string));
            dt.Columns.Add("Comments", typeof(string));
            dt.Columns.Add("CountyName", typeof(string));
            dt.Columns.Add("LocalCD", typeof(string));
            dt.Columns.Add("LocalName", typeof(string));
            dt.Columns.Add("LocRate", typeof(string));
            dt.Columns.Add("ResInd", typeof(string));
            dt.Columns.Add("SchlRate", typeof(string));
            dt.Columns.Add("State", typeof(string));
            dt.Columns.Add("W2Name", typeof(string));
            dt.Columns.Add("WhRate", typeof(string));
            string na = "n/a";
            foreach (CityTaxInfo objCityTax in list)
            {
                DataRow row = dt.NewRow();
                row["CityTaxID"] = objCityTax.CityTaxID;
                row["AdditionalJur"] = string.IsNullOrEmpty(objCityTax.AdditionalJur) ? na : objCityTax.AdditionalJur;
                row["Comments"] = string.IsNullOrEmpty(objCityTax.Comments) ? na : objCityTax.Comments;
                row["CountyName"] = string.IsNullOrEmpty(objCityTax.CountyName) ? na : objCityTax.CountyName;
                row["LocalCD"] = string.IsNullOrEmpty(objCityTax.LocalCD) ? na : objCityTax.LocalCD;
                row["LocalName"] = string.IsNullOrEmpty(objCityTax.LocalName) ? na : objCityTax.LocalName;
                row["LocRate"] = string.IsNullOrEmpty(objCityTax.LocRate) ? na : objCityTax.LocRate;
                row["ResInd"] = string.IsNullOrEmpty(objCityTax.ResInd) ? na : objCityTax.ResInd;
                row["SchlRate"] = string.IsNullOrEmpty(objCityTax.SchlRate) ? na : objCityTax.SchlRate;
                row["State"] = string.IsNullOrEmpty(objCityTax.State) ? na : objCityTax.State;
                row["W2Name"] = string.IsNullOrEmpty(objCityTax.W2Name) ? na : objCityTax.W2Name;
                row["WhRate"] = string.IsNullOrEmpty(objCityTax.WhRate) ? na : objCityTax.WhRate;
                dt.Rows.Add(row);
            }
            // Bind            
            mDataDataList.DataSource = dt;
            mDataDataList.DataBind();
            // show the result
            mDataDataList.Visible = true;

            // show print link
            mPrintTable.Visible = true;
            return dt;
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Page_Load runs when the control is loaded.
        /// </summary>
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                RegisterModalBox();
                PopulateTemplate();
                SetPressDownEvent();
                if (!IsPostBack)
                {
                    PopulateStates();
                }
                SetComboIndex(mStateDropDown, mStateDropDown.Text);
                InitInfo();                
            }
            catch (Exception exc) // Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void mSearchButton_Click(object sender, EventArgs e)
        {
            // reset the pressdownevent
            SetPressDownEvent();

            // when both City and Code are empty
            if (string.IsNullOrEmpty(mCityTextBox.Text) && string.IsNullOrEmpty(mCodeTextBox.Text))
            {
                return;
            }

            Search(mStateDropDown.Text, mCityTextBox.Text, mCodeTextBox.Text);

            SetComboIndex(mStateDropDown, mStateDropDown.Text);
        }

        #endregion

        #region Optional Interfaces


        /// <summary>
        /// Gets the module actions.
        /// </summary>
        /// <value>The module actions.</value>
        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile)
                    , ModuleActionType.AddContent, "", "", this.EditUrl("UploadData"), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        #endregion

        
    }
}